package cn.yjh.server.net;

import java.nio.ByteBuffer;

import java.util.concurrent.ExecutorService;

import cn.yjh.server.Handler;
import cn.yjh.server.Reader;
import cn.yjh.server.Writer;
import cn.yjh.support.ServiceHandler;


/**
 * @DESC:
 * @AUTHOR: YouJinhua
 * @DATE: 2021/12/17 16:42
 * @VERSION: 1.0
 */
public abstract class AbstractHandler implements Reader, Writer, Handler {

    protected ByteBuffer inCache = ByteBuffer.allocate(655);
    //protected ByteBuffer inCache = ByteBuffer.allocate(8196);

    protected ByteBuffer outCache = ByteBuffer.allocate(8196);

    protected ExecutorService workers;

    protected SlaveReactor reactor;

    protected Thread reactorThread;

    // 读就绪
    protected final  int READ = 1;

    // 处理就绪
    protected final  int PROCESS = 2;

    // 处理中
    protected final  int PROCESSING = 3;

    // 写就绪
    protected final  int WRITE = 4;

    // 所有连接完成后都是从读取数据开始的
    protected int status = READ;

    protected ServiceHandler serviceHandler = null;

    public AbstractHandler(SlaveReactor reactor, Thread reactorThread, ExecutorService workers, ServiceHandler serviceHandler) {
        this.reactorThread = reactorThread;
        this.reactor = reactor;
        this.workers = workers;
        this.serviceHandler = serviceHandler;
    }

    @Override
    public void process() {
        switch (status) {
            case READ:
                read();
                break;
            case PROCESS:
                handle();
                break;
            case WRITE:
                write();
                break;
            default:
        }
    }


    private void handle() {
        // 将当前状态设置为处理中，避免重复处理
        status = PROCESSING;
        // 异步处理
        try {
            // 此处使用 submit 提交任务，避免处理业务逻辑时出问题后，线程终止
            workers.submit(this::doProcess).get();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    abstract void doProcess();

}
